<?php

declare(strict_types=1);

namespace App\Core;

final class Router
{
    /** @var array<string, array<string, mixed>> */
    private static array $routes = [
        'GET' => [],
        'POST' => [],
        'PUT' => [],
        'PATCH' => [],
        'DELETE' => [],
    ];

    /**
     * @param callable|string $handler 闭包或 "Controller@method"
     */
    public static function add(string $method, string $path, $handler): void
    {
        $method = strtoupper($method);
        if (!isset(self::$routes[$method])) {
            self::$routes[$method] = [];
        }
        self::$routes[$method][$path] = $handler;
    }

    /**
     * @param callable|string $handler
     */
    public static function get(string $path, $handler): void
    {
        self::add('GET', $path, $handler);
    }

    /**
     * @param callable|string $handler
     */
    public static function post(string $path, $handler): void
    {
        self::add('POST', $path, $handler);
    }

    /**
     * 简单匹配：优先精确匹配；支持 /post/{id} 形式的占位符
     * @return array{0:mixed|null,1:array<int,string>}
     */
    public static function match(string $method, string $path): array
    {
        $method = strtoupper($method);
        $routes = self::$routes[$method] ?? [];

        // 规范化路径：移除末尾斜杠（除了根路径）
        if ($path !== '/' && str_ends_with($path, '/')) {
            $path = rtrim($path, '/');
        }

        if (isset($routes[$path])) {
            return [$routes[$path], []];
        }

        foreach ($routes as $routePath => $handler) {
            $pattern = preg_replace('#\{[^/]+\}#', '([^/]+)', $routePath);
            $pattern = '#^' . $pattern . '$#';
            if (preg_match($pattern, $path, $m)) {
                array_shift($m);
                return [$handler, $m];
            }
        }

        return [null, []];
    }
}
